//
//  SearchViewController.m
//  ToYourHeartNews
//
//  Created by XJing on 16/1/28.
//  Copyright © 2016年 www.lanou3g.com 蓝鸥. All rights reserved.
//

#import "SearchViewController.h"
#import "SearchTableViewCell.h"
#import "AfNetWorkingHandler.h"
#import "AllModel.h"
#import "AllDetailModel.h"
#import "SearchModel.h"
#import "PushWebViewVC.h"
@interface SearchViewController ()<UISearchBarDelegate, UISearchResultsUpdating, UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong)UISearchController *search;/**< 搜索控制视图 */
@property (nonatomic, strong)NSString *strHight;/**< 高亮用字符串 保存搜索信息 */
@property (nonatomic, strong)UIWebView *webVC;
@property (nonatomic, strong)UITableView *tableView;/**< 用来显示搜索出来的内容 */
@property (nonatomic, strong)NSMutableArray *dataArr;/**< 保存点击进入详情的数据 */
@property (nonatomic, strong)NSMutableArray *searchArr;/**< 接收搜索出来的数据 */
@property (nonatomic, strong)NSMutableArray *idArr;/**< 保存所有内容的id */
@property (nonatomic, strong)NSMutableArray *systemIdArr;/**< 存放系统中所有id */
@end

@implementation SearchViewController
- (void)dealloc
{
    [_dingyueArr release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //    搜索步骤:
    //    1.初始化搜索视图
    //    2.搜索视图签订协议
    //    3.设置搜索视图
    //    4.在搜索视图的协议方法中 获取输入内容 对搜索内容解析数据 刷新tableView
    //    5.在tableVIewCell方法中设置高亮 NSMutableAttributedString
    self.search = [[UISearchController alloc]initWithSearchResultsController:nil];
    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"iconfont-newlisticon06"] style:UIBarButtonItemStylePlain target:self action:@selector(backAction)] autorelease];
    //签订协议
    _search.searchResultsUpdater = self;
    //屏幕变灰 默认是yes tableView不能拉
    _search.dimsBackgroundDuringPresentation = NO;
    //设置点击搜索框时 隐藏导航栏
    _search.hidesNavigationBarDuringPresentation = NO;
    //占位符 默认search
    _search.searchBar.placeholder = @"搜索内容";
    //搜索栏的风格
    _search.searchBar.searchBarStyle = UISearchBarStyleMinimal;
    //把搜索视图加到导航栏上
    self.navigationItem.titleView = _search.searchBar;
    //创建tableView
    [self creatTableView];
    
    
    //            [_search release];
    
//    dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//    //添加任务
//    dispatch_async(globalQueue, ^{
//        //处理数据
//        [self dataHandler];
//        //在子线程中 获取主队列
//        dispatch_queue_t mainQueue = dispatch_get_main_queue();
//        dispatch_async(mainQueue, ^{
//            
//           //得到搜索到的内容的model model的weburl属性是webView
//            for (NSString *str in _idArr) {
//                for (AllDetailModel *m in _systemIdArr) {
//                    if ([str isEqualToString:m.pk]) {
//                        [_dataArr addObject:m];
//                    }
//                }
//            }
//            
//        });
//    });
    
    
    

    
}
-(void)creatTableView
{
    self.tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    [_tableView release];
    [_tableView registerClass:[SearchTableViewCell class] forCellReuseIdentifier:@"cellSearch"];
    _tableView.contentInset = UIEdgeInsetsMake(0, 0, 55, 0);
    [_tableView release];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _searchArr.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    PushWebViewVC *detailVC = [[PushWebViewVC alloc]init];
    //获取点击的cell的详情页数据
    SearchModel *m = _searchArr[indexPath.row];
    for (AllDetailModel *model in _dataArr) {
        if ([m.mid isEqualToString:model.pk]) {
            detailVC.pathstr = model.weburl;
        }
    }
    [self.navigationController pushViewController:detailVC animated:YES];
    [detailVC release];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SearchTableViewCell *cell = [_tableView dequeueReusableCellWithIdentifier:@"cellSearch"];
    SearchModel *m = _searchArr[indexPath.row];
    [cell.titleWeb loadHTMLString:m.s_title baseURL:[NSURL URLWithString:m.s_title]];
    [cell.detailWeb loadHTMLString:m.s_content baseURL:[NSURL URLWithString:m.s_content]];
    //让图片匹配webView的大小
    NSString *img = [@"<head><style>img{max-width:50px !important;}</style></head> " stringByAppendingString:m.s_imghtml];
    [cell.pictureWeb loadHTMLString:img baseURL:[NSURL URLWithString:img]];
    return cell;
}
-(void)backAction
{
    [self dismissViewControllerAnimated:YES completion:^{
        //
    }];
}
#pragma mark - 实现搜索栏协议方法
//只要搜索栏有内容 就执行下面的方法
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
    
    //将搜索内容转换为字符串
    //等同于 获取搜索的信息 显示的文本
    self.strHight = [self.search.searchBar text];
    if ([_strHight containsString:@" "]) {
        //判断如果有空格不执行
        //没有执行以下程序
        //不写这个判断 打空格就会崩溃
    }else{
        //中文转码
        NSString *urlStr = [_strHight stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:_strHight]];
        NSLog(@"%@", urlStr);
        //拼接网址
        //订阅的文章中
         NSString *str = [@"http://search.myzaker.com/api/?c=main&act=getArticles&keyword=%E4%BD%A0&app_ids=310000%2C660%2C4%2C13%2C11426%2C10530%2C10599%2C11656%2C11919%2C12125%2C11878%2C12039%2C11826%2C12063%2C10721%2C10318%2C11609%2C981%2C11944&_appid=iphone&_dev=iPhone%2C8.4.1&_os_name=&_os=&_uid=11245841&_udid=ECFC153B-2246-4EB0-8D9F-510516697A0C&_v=6.4.6&_version=6.45"stringByReplacingOccurrencesOfString:@"keyword=%E4%BD%A0" withString:[NSString stringWithFormat:@"keyword=%@", urlStr]];
        [AfNetWorkingHandler GetWithStr:str complection:^(id result) {
            //
            NSArray *arr = result[@"data"][@"list"];
            self.searchArr = [SearchModel modelHanderWithArray:arr];
            self.idArr = result[@"data"][@"article_ids"];
            
            //数据处理获取系统的中所有model
//            [self dataHandler];
//            //得到搜索到的内容的model model的weburl属性是webView
//            for (NSString *str in _idArr) {
//                for (AllDetailModel *m in _systemIdArr) {
//                    if ([str isEqualToString:m.pk]) {
//                        [_dataArr addObject:m];
//                    }
//                }
//            }

            [_tableView reloadData];
            
            
        }];
        
    }
}
-(void)sonLines
{
//    NSThread *newThread = [[NSThread alloc]initWithTarget:self selector:@selector(dataHandler) object:nil];
//    newThread.name = @"子线程呀";
//    [newThread start];
//    dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//    //添加任务
//    dispatch_async(globalQueue, ^{
//        //处理数据
//        [self dataHandler];
//        //在子线程中 获取主队列
//        dispatch_queue_t mainQueue = dispatch_get_main_queue();
//        dispatch_async(mainQueue, ^{
//            
//            //得到搜索到的内容的model model的weburl属性是webView
//            for (NSString *str in _idArr) {
//                for (AllDetailModel *m in _systemIdArr) {
//                    if ([str isEqualToString:m.pk]) {
//                        [_dataArr addObject:m];
//                    }
//                }
//            }
//
//        });
//    });

    
    
    
}
//数据处理
-(void)dataHandler
{
    self.systemIdArr = [NSMutableArray array];
    NSMutableArray *strArr = [NSMutableArray array];
    //遍历系统里的内容
    for (AllModel *model in _dingyueArr) {
        NSArray *arr = model.sons;
        for (NSDictionary *dic in arr) {
            NSLog(@"%@", dic);
            NSString *str = dic[@"api_url"];//专题
            if (str.length != 0) {
                [strArr addObject:str];
            }
            
            
        }
    }
    NSLog(@"%@", strArr);
    for (NSString *s in strArr) {
        NSLog(@"%@", s);
        [AfNetWorkingHandler GetWithStr:s complection:^(id result) {
            //
            NSArray *arr = result[@"data"][@"articles"];
            NSArray *arrDaiti = [AllDetailModel modelHanderWithArray:arr];
            for (AllDetailModel *m in arrDaiti) {
                [_systemIdArr addObject:m];
            }
            NSLog(@"%@", _systemIdArr);
            [_tableView reloadData];
            
            
        }];
    }
    
 
    //得到搜索到的内容的model model的weburl属性是webView
//    for (NSString *str in _idArr) {
//        for (AllDetailModel *m in _systemIdArr) {
//            if ([str isEqualToString:m.pk]) {
//                [_dataArr addObject:m];
//            }
//        }
//    }
    //搜索的内容
//    NSString *searchAtr = @"http://iphone.myzaker.com/zaker/article_mongo.php?_appid=iphone&_bsize=640_1136&app_id=1238&m=1453943571&pk=56a96f8a1bc8e0d67b000009&show_related=Y&style_v=2";
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
